/****************************************************
	文件：MonoSingleton.cs
	作者：HuskyT
	邮箱：1005240602@qq.com
	日期：2020/4/3 16:33:25
	功能：Mono 单例
*****************************************************/

using UnityEngine;
using HTFW.Logger;

namespace HTFW.Utility.Global
{
    public class MonoSingleton<T> : MonoBehaviour where T : MonoSingleton<T>
    {
        private static T mInstance;

        public static T Instance
        {
            get
            {
                if (mInstance == null)
                {
                    T[] instanceArray = FindObjectsOfType<T>(); //根据类型 T 搜索实例
                    string typeName = typeof(T).Name;
                    if (instanceArray == null || instanceArray.Length == 0) //场景中 无实例
                    {
                        GameObject instanceGO = GameObject.Find(typeName); //根据类型名搜索场景中 GameObject
                        if (instanceGO == null) //无同名 GameObject
                        {
                            instanceGO = new GameObject(typeName);
                            DontDestroyOnLoad(instanceGO); //切换场景 单例不销毁
                        }

                        mInstance = instanceGO.AddComponent<T>(); //添加实例
                    }
                    else if (instanceArray.Length == 1) //场景中 有一个实例
                    {
                        mInstance = instanceArray[0];
                    }
                    else //场景中 有多个实例
                    {
                        HLog.Warning("存在多个 GameObject 挂载有单例：" + typeof(T).Name);
                        mInstance = instanceArray[0];
                    }
                }

                return mInstance;
            }
        }

        protected virtual void Awake()
        {
            if (mInstance == null)
            {
                mInstance = (T) this;
                DontDestroyOnLoad(gameObject);
            }
            else
                Destroy(gameObject);
        }

        protected virtual void OnDestroy()
        {
            mInstance = null;
        }
    }
}